package com.food.service.impl;

import com.food.common.Result;
import com.food.dto.UserLoginDTO;
import com.food.dto.UserRegisterDTO;
import com.food.mapper.UserMapper;
import com.food.mapper.UserGoalMapper;
import com.food.mapper.UserProfileMapper;
import com.food.model.User;
import com.food.model.UserGoal;
import com.food.model.UserProfile;
import com.food.service.EmailService;
import com.food.service.UserService;
import com.food.service.VerificationCodeService;
import com.food.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.io.File;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserGoalMapper userGoalMapper;
    
    @Autowired
    private UserProfileMapper userProfileMapper;
    
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    
    @Autowired
    private EmailService emailService;

    @Autowired
    private VerificationCodeService verificationCodeService;

    private static final String DEFAULT_AVATAR = "/images/avatar/default.jpg";

    private void validateGender(String gender) {
        if (gender != null && !gender.equals(UserProfile.GENDER_MALE) 
            && !gender.equals(UserProfile.GENDER_FEMALE)
            && !gender.equals(UserProfile.GENDER_UNSET)) {
            throw new RuntimeException("性别只能是 '男'、'女' 或 '未设置'");
        }
    }

    @Override
    @Transactional
    public Result<?> register(UserRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(registerDTO.getUsername()) != null) {
            return Result.error("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (userMapper.findByEmail(registerDTO.getEmail()) != null) {
            return Result.error("邮箱已被注册");
        }

        // 在创建用户资料前验证性别
        validateGender(registerDTO.getGender());

        // 直接使用明文密码，不进行加密
        // 插入用户记录，使用默认头像
        userMapper.insertWithAvatar(registerDTO, DEFAULT_AVATAR);

        // 创建用户档案
        UserProfile profile = new UserProfile();
        profile.setUserId(registerDTO.getUserId());
        profile.setName("");
        profile.setGender("未设置");
        profile.setAge(0);
        profile.setHeight(0.0);
        profile.setWeight(0.0);
        profile.setActivityLevel(UserProfile.DEFAULT_ACTIVITY_LEVEL);
        userProfileMapper.insert(profile);

        return Result.success(null);
    }

    @Override
    public Result<?> login(UserLoginDTO loginDTO) {
        try {
            System.out.println("尝试登录用户: " + loginDTO.getUsername());  // 添加日志
            User user = userMapper.findByUsername(loginDTO.getUsername());
            System.out.println("查询结果: " + (user != null ? "找到用户" : "未找到用户"));  // 添加日志

            if (user == null) {
                return Result.error("用户名不存在");
            }

            // 直接比较明文密码
            if (!loginDTO.getPassword().equals(user.getPassword())) {
                return Result.error("密码错误");
            }

            // 密码验证成功，直接返回用户ID
            return Result.success(user.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    @Override
    public Result<?> getProfile(Integer userId) {
        try {
            UserProfile profile = userProfileMapper.findByUserId(userId);
            if (profile == null) {
                profile = new UserProfile();
                profile.setUserId(userId);
                userProfileMapper.insert(profile);
                profile = userProfileMapper.findByUserId(userId);
            }
            return Result.success(profile);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取用户档案失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<?> updateProfile(UserProfile profile) {
        if (profile == null) {
            return Result.error("档案数据不能为空");
        }
        
        // 检查用户档案是否存在
        UserProfile existingProfile = userProfileMapper.findByUserId(profile.getUserId());
        if (existingProfile == null) {
            // 如果档案不存在，设置默认值
            if (profile.getName() == null) profile.setName("");
            if (profile.getGender() == null) profile.setGender("未设置");
            if (profile.getAge() == null) profile.setAge(0);
            if (profile.getHeight() == null) profile.setHeight(0.0);
            if (profile.getWeight() == null) profile.setWeight(0.0);
            if (profile.getActivityLevel() == null) profile.setActivityLevel("中等");
            userProfileMapper.insert(profile);
        } else {
            // 如果档案存在，保留原有值
            if (profile.getName() == null) profile.setName(existingProfile.getName());
            if (profile.getGender() == null) profile.setGender(existingProfile.getGender());
            if (profile.getAge() == null) profile.setAge(existingProfile.getAge());
            if (profile.getHeight() == null) profile.setHeight(existingProfile.getHeight());
            if (profile.getWeight() == null) profile.setWeight(existingProfile.getWeight());
            if (profile.getActivityLevel() == null) profile.setActivityLevel(existingProfile.getActivityLevel());
            userProfileMapper.update(profile);
        }
        
        return Result.success(null);
    }

    @Override
    @Transactional
    public Result<?> setGoal(Integer userId, UserGoal goal) {
        goal.setUserId(userId);
        userGoalMapper.insertOrUpdate(goal);
        return Result.success(null);
    }

    @Override
    public Result<?> getGoal(Integer userId) {
        UserGoal goal = userGoalMapper.findByUserId(userId);
        return Result.success(goal);
    }

    @Override
    @Transactional
    public Result<?> updatePassword(Integer userId, String oldPassword, String newPassword) {
        User user = userMapper.findById(userId);
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return Result.error("原密码错误");
        }
        
        String encodedPassword = passwordEncoder.encode(newPassword);
        userMapper.updatePassword(userId, encodedPassword);
        return Result.success(null);
    }

    @Override
    public Result<?> resetPassword(String email) {
        User user = userMapper.findByEmail(email);
        if (user == null) {
            return Result.error("邮箱不存在");
        }
        String token = JwtUtil.generateToken(user.getUserId());
        emailService.sendPasswordResetLink(email, token);
        return Result.success(null);
    }

    @Override
    public Result<?> verifyEmail(String email, String code) {
        if (verificationCodeService.verifyCode(email, code)) {
            return Result.success(null);
        }
        return Result.error("验证码错误或已过期");
    }

    @Override
    public Result<?> sendVerificationCode(String email) {
        String code = verificationCodeService.generateCode(email);
        emailService.sendVerificationCode(email, code);
        return Result.success(null);
    }

    @PostConstruct
    public void init() {
        // 检查默认头像是否存在
        Resource defaultAvatar = new ClassPathResource("static/images/avatar/default.jpg");
        if (!defaultAvatar.exists()) {
            logger.error("默认头像文件不存在：{}", DEFAULT_AVATAR);
        }
    }
} 